package moocloudstudio.minder.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import moocloudstudio.minder.entity.MinderUser;
import moocloudstudio.minder.model.UserModel;
import moocloudstudio.minder.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;

// 不加@Validated注解参数校验不生效
@Validated
@Api
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录", notes = "用户登录功能")
    @PostMapping("/login")
    public SaResult login(@ApiParam("用户名") @NotBlank(message = "用户名不能为空") String username,
                          @ApiParam("密码") @NotBlank(message = "密码不能为空") String password){
        // 登录信息检查
        userService.checkUserLogin(username, password);
        MinderUser user = userService.findUserByUsername(username);
        userService.checkUserAllowLogin(user.getId());
        // 登录
        StpUtil.login(user.getId());
        UserModel userModel = UserModel.create(user);
        userModel.setTokenInfo(StpUtil.getTokenInfo());

        return SaResult.data(userModel);
    }

    @ApiOperation(value = "注销", notes = "退出登录")
    @GetMapping("/logout")
    public SaResult logout(){
        String userId = StpUtil.getLoginIdAsString();
        StpUtil.logout(userId);
        return SaResult.ok();
    }


    @ApiOperation(value = "注册", notes = "用户注册功能")
    @PostMapping("/register")
    public SaResult register(@ApiParam("用户名") @NotBlank(message = "用户名不能为空") String username,
                             @ApiParam("密码") @NotBlank(message = "密码不能为空") String password,
                             @ApiParam("昵称") @NotBlank(message = "昵称不能为空") String nickname){

        MinderUser user = userService.register(username, password, nickname);
        UserModel userModel = UserModel.create(user);
        return SaResult.data(userModel).setMsg("注册成功");
    }

//
//    @ApiOperation(value = "删除用户", notes = "此接口仅限测试使用")
//    @DeleteMapping
//    public SaResult delete(String id){
//        userService.deleteById(id);
//        return SaResult.ok("删除成功");
//    }
}
